home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Help: 2 short functions
- Date: 29 Mar 1996 22:11:12 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4jija0INNqnn@keats.ugrad.cs.ubc.ca>
- References: <4ji734$n6v@masala.cc.uh.edu>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4ji734$n6v@masala.cc.uh.edu>,
- odie garfield <st7jr@Rosie.UH.EDU> wrote:
- >Hi, I have two functions that I'm not too sure about.
- >The first one:
- >
- >char *get_filename(void)
- >{
- > char string[20],*stringp;
- > scanf("%s",string);
-
- should be: scanf("%19s",string);
-
- Watch for buffer overflows, they are evil!
-
- > stringp=&string[0];
-
- This is equivalent to writing: stringp=string
-
- > return stringp;
-
- This is equivalent, therefore, to: return string;
-
- And it is extremely illegal. The string object ceases to exist when the
- function exits. It is local to the function.
-
- >}
- >I'm want the function to read in a string and return a pointer to that string.
- >Am I doing it correctly?
-
- No. You must either declare the string array static, or dynamically allocate it
- with malloc():
-
- static string[20];
-
- OR
-
- char *string = malloc(20);
-
- The pitfall of declaring it static is that then it names only one object. Each
- time you call the function, string is the same object with the same address.
- You overwrite the previous contents each time you call scanf. This is fine as
- long as the caller understands this and takes care to copy the string to a safe
- place.
-
- The pitfalls of using dynamic allocation is that you have to watch out for
- memory leaks and other problems. Someone has to free() the storage once it is
- not needed anymore.
-
- By the way, a good design is to let the _caller_ specify the storage buffer:
-
- void get_filename(char *buffer, int bufsize)
-
- {
- fgets(buffer, bufsize, stdin);
- }
-
- >My second function is related to the first function:
- >
- >FILE *open_file(char *filenamep)
- >{
- > FILE *fp;
- > fp=fopen("??????","r");
- > return fp;
- >}
-
- That could be rewritten: { return fopen(filenamep, "r"); }
-
- It is a valid, though useless wrapper for fopen().
-
- >In this 2nd function, I want to open a file using the pointer to a string I
- >got from the first function. But I don't know exactly how to do this. Any help
- >would be appreciated. Thanks.
-
- As I wrote above.
-
- --
-
-